/*
 * Copyright (c) 2021 The red-star Project
 *
 * Licensed under the Apache License, version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inyourcode.core.db;

import com.inyourcode.core.threads.ConsumerTask;
import com.inyourcode.core.threads.api.HashExecutor;
import com.inyourcode.core.transport.session.SessionService;
import com.inyourcode.core.transport.session.api.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * 数据存储
 * @author JackLei
 */
public class DataSaveProcessor {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataSaveProcessor.class);
    private long dbStorageInterval ;
    private long tickCount;
    private HashExecutor hashExecutor;

    public DataSaveProcessor(long dbStorageInterval, HashExecutor fixedExecutor) {
        this.dbStorageInterval = dbStorageInterval;
        this.hashExecutor = fixedExecutor;
    }

    public void tick() {
        tickCount++;
        Collection<Session> sessions = SessionService.getAll();
        for (Session session : sessions) {
            if (session.state() != BasicDataContext.STATE_LOADED) {
                continue;
            }

            Long sessionId = session.getId();
            long playerTickHash = tickCount + sessionId.hashCode();
            boolean isSave = playerTickHash % this.dbStorageInterval == 0;
            if (isSave) {
                session.execute(()->{
                        session.saveAllData(hashExecutor, ConsumerTask.DEFALUT);
                });
            }
        }
    }

}
